#########4.1 自定义函数#######
#为给定数据框中的数据计算平均值和误差棒的上下线

##普通代码
df <- data.frame(TB = c(5.8, 6.8, 5.7, 6.2, 6.4),
                 Ht = c(5.0, 5.6, 4.7, 5.5, 5.7),
                 RL = c(4.1, 6.6, 5.2, 5.9, 4.8))
df

mean_TB <- mean(df$TB)
se_TB   <- sd(df$TB)/(length(df$TB)^0.5)
up_TB   <- mean_TB + se_TB
down_TB <- mean_TB - se_TB
TB <- c(mean_TB, se_TB, up_TB, down_TB)
TB

mean_Ht <- mean(df$Ht)
se_Ht   <- sd(df$Ht)/(length(df$Ht)^0.5)
up_Ht   <- mean_Ht + se_Ht
down_Ht <- mean_Ht - se_Ht
Ht <- c(mean_Ht, se_Ht, up_Ht, down_Ht)
Ht

#…………………………代码重复，臃肿且可读性差，不便于修改，不便迁移
#自定义函数打包
ebar <- function(data) {
  mean <- mean(data)
  se   <- sd(data)/(length(data)^0.5)
  up   <- mean + se
  down <- mean - se
  return(c(mean, se, up, down))
}

ebar(df$TB)
ebar(df$Ht)
ebar(df$RL) #返回的结果可以赋值保存，如构建数据框

errorbar <- data.frame(TB = ebar(df$TB),
                       Ht = ebar(df$Ht),
                       RL = ebar(df$RL))
errorbar

#########4.2 核心句法结构#######

#1. if
#林龄划分
# 设定某一样地的林龄（单位：年）
stand_age <- 65  

if (stand_age <= 40) {
  succession_stage <- "幼龄林"
} else if (stand_age <= 80) {
  succession_stage <- "中龄林"
} else if (stand_age <= 100) {
  succession_stage <- "近熟林"
} else if (stand_age <= 140){
  succession_stage <- "成熟林"
} else {
  succession_stage <- "过熟林"
}

cat("该样地林龄为", stand_age, "年，龄组为：", succession_stage)

stand_age <- 132 

#2. for语句
stand_age <- c(52, 78, 144, 102, 29)
succession_stage <- c()     #创建空的龄组向量
for (i in c(1:5)) {         #也可以用c(1:length(stand_age))
  if (stand_age[i] <= 40) {
    succession_stage[i] <- "幼龄林"
  } else if (stand_age[i] <= 80) {
    succession_stage[i] <- "中龄林"
  } else if (stand_age[i] <= 100){
    succession_stage[i] <- "近熟林"
  } else if (stand_age[i] <= 140){
    succession_stage[i] <- "成熟林"
  } else {
    succession_stage[i] <- "过熟林"
  }
}

succession_stage

data.frame(林龄 = stand_age,
           龄组 = succession_stage)

#3. while语句
stand_age <- c(52, 78, 144, 102, 29)
succession_stage <- c()
i <- 1                         #从第1个元素开始计算
while(!is.na(stand_age[i])) {  #当stand_age中第i个元素不为NA时，进行下面的运算
  if (stand_age[i] <= 40) {
    succession_stage[i] <- "幼龄林"
  } else if (stand_age[i] <= 80) {
    succession_stage[i] <- "中龄林"
  } else if (stand_age[i] <= 100) {
    succession_stage[i] <- "近熟林"
  } else if (stand_age[i] <= 140){
    succession_stage[i] <- "成熟林"
  } else {
    succession_stage[i] <- "过熟林"
  }
  i <- i+1
}

succession_stage

data.frame(林龄 = stand_age,
           龄组 = succession_stage)

#4. 向量化操作
scores <- c(85, 72, 90, 68)
# 向量化判断：直接对向量每个元素判断
grades <- ifelse(scores >= 80, "优秀", ifelse(scores >= 60, "及格", "不及格"))
print(grades)

